import { useContext, useEffect, useState, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useSearchParams } from 'react-router-dom'
import { ApiContext } from '@/api/ApiHub'
import {
  changeSystem,
  changeSelectedWidgetIds,
  changeWidgets,
  changeLayouts,
  changeGlobalValue,
  changeDelWidgets
} from '@/store/modules/core'
import useQuery from './hooks/useQuery'
import Header from './components/Header'
import Panel from './Panel'
import Layout from './Layout'
import styles from './index.module.less'

const BiCore = () => {
  const dispatch = useDispatch()
  const { meta, widgets, layouts, globalValue, delWidgets } = useSelector((state) => state.core)
  const api = useContext(ApiContext)
  const { allChartQuery } = useQuery()

  const [searchParams] = useSearchParams()
  const dashboardId = +searchParams.get('id')

  const [name, setName] = useState('新建仪表盘')

  useEffect(() => {
    dashboardId && getDashboard()
  }, [dashboardId])

  const getDashboard = async () => {
    const { name, config, widgets: initWidgets, system } = await api.getDashboard({ dashboardId })
    const { layouts, globalValue } = config
    setName(name)
    dispatch(changeLayouts(layouts))
    dispatch(changeGlobalValue(globalValue))
    dispatch(changeSystem(system))
    dispatch(changeSelectedWidgetIds([]))
    dispatch(changeWidgets(initWidgets))
    dispatch(changeDelWidgets({}))
    initWidgetsQuery(initWidgets)
  }

  const initWidgetsQuery = (initWidgets = {}) => {
    allChartQuery(initWidgets)
  }

  const setDashboard = async () => {
    const data = await api.setDashboard({ name, meta, widgets, layouts, globalValue, delWidgets })
    let newWidgets = { ...widgets }
    data.forEach(({ widgetIdSystem, widgetId }) => {
      const widget = newWidgets[widgetId]
      newWidgets[widgetId] = {
        ...widget,
        meta: {
          ...widget.meta,
          widgetIdSystem
        }
      }
    })
    dispatch(changeSelectedWidgetIds([]))
    dispatch(changeWidgets(newWidgets))
    dispatch(changeDelWidgets({}))
  }

  return (
    <div className={styles['bi-core']}>
      <Header value={name} onChange={(e) => setName(e.target.value)} onSave={setDashboard} />
      <div className={styles.container}>
        <Panel />
        <Layout />
      </div>
    </div>
  )
}

export default BiCore
